import React, { Component } from 'react';
import { messages } from 'share/common';
import 'styles/expense/expense-main-util.scss';
import TemplateHoc from '../component/template-hoc';
import shallowEqual from '../component/shallowEqual';

@TemplateHoc
class ExpenseUtil extends Component {

  static contextTypes = {
    nowExpenseDataSource: React.PropTypes.array,
    isAuditEditable: React.PropTypes.bool,
    currentExpenseIndex: React.PropTypes.number,
  };

  buttons = [
    {
      name: messages('common.back')/*返回*/,
      type: 'back',
      className: 'expense-main-util-back',
    },
    {
      name: messages('common.edit')/*编辑*/,
      type: 'edit',
      className: 'expense-main-util-edit'
    },
    {
      name: messages('expense-1.key704')/*上一页*/,
      type: 'up',
      className: 'expense-main-util-previous',
    },
    {
      name: messages('expense-1.key705')/*下一页*/,
      type: 'down',
      className: 'expense-main-util-next',
    }
  ];

  handleClick = (type) => {
    this.props.handleUtil(type);
  };

  handleDisabled = (type) => {
    const { currentExpenseIndex, nowExpenseDataSource } = this.context;
    if (type === 'up' && currentExpenseIndex === 0) {
      return true;
    }
    return type === 'down' && currentExpenseIndex === nowExpenseDataSource.length - 1;
  };

  shouldComponentUpdate(nextProps, nextState, nextContext) {
    return !shallowEqual(this.props, nextProps) ||
      !shallowEqual(this.state, nextState) ||
      !shallowEqual(this.context, nextContext);
  }

  render() {
    const { isAuditEditable } = this.context;
    return (
      <section className="expense-main-util">
        {
          this.buttons
            .filter(item => isAuditEditable || !isAuditEditable && item.type !== 'edit')
            .map((item) => (
              <div
                className="expense-main-util-button"
                disabled={this.handleDisabled(item.type)}
                onClick={() => this.handleClick(item.type)}
              >
                <div className={`expense-main-util-icon ${item.className}`}/>
                <span>{item.name}</span>
              </div>
            ))
        }
      </section>
    );
  }
}

ExpenseUtil.propTypes = {};

export default ExpenseUtil;
